package com.idlecode.config.template;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.rmi.ServerException;
import java.util.List;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.idlecode.statics.TemplateInfoStatic;
import com.idlecode.util.StreamUtil;

/**
 * 代码生成配置内容
 */
public class GeneratorConfig {
	private static String template = "/resources/template";

	public GeneratorInfo getGeneratorConfig(List<String> selectedGenFileItems, boolean isFormatException) throws ServerException {
		// 模板路径，如果不是以/结尾，则添加/
		if (!CharSequenceUtil.endWith(template, '/')) {
			template = template + "/";
		}

		// 模板配置文件
		try (InputStream isConfig = this.getClass().getResourceAsStream(template + "initial-config.json")) {
			if (isConfig == null) {
				throw new ServerException("模板配置文件config.json不存在");
			}
			// 读取模板配置文件
			String configContent = StreamUtil.copyToString(isConfig, StandardCharsets.UTF_8);
			// GeneratorInfo generator = JsonUtil.parseObject(configContent,
			// GeneratorInfo.class);
			GeneratorInfo generator = JSONUtil.toBean(configContent, GeneratorInfo.class);
			generator.setTemplates(TemplateInfoStatic.getTemplates(selectedGenFileItems, isFormatException));
			for (TemplateInfo templateInfo : generator.getTemplates()) {
				// 模板文件
				InputStream isTemplate = this.getClass().getResourceAsStream(template + templateInfo.getTemplateName());
				if (isTemplate == null) {
					throw new ServerException("模板文件 " + templateInfo.getTemplateName() + " 不存在");
				}
				// 读取模板内容
				String templateContent = StreamUtil.copyToString(isTemplate, StandardCharsets.UTF_8);

				templateInfo.setTemplateContent(templateContent);
			}
			return generator;
		} catch (Exception e) {
			if (e instanceof ServerException) {
				throw (ServerException)e;
			}
			e.printStackTrace();
			throw new ServerException("读取config.json配置文件失败");
		}
	}

}
